<template>
  <PageCard title="文本转语音">
    <!-- 主要功能区 -->
    <div class="tool-container">
      <n-grid :cols="12" :x-gap="24" :y-gap="24">
        <!-- 左侧：TTS功能区 -->
        <n-gi :span="isMobile ? 12 : 8">
          <div class="tts-function-area">
        <!-- 文本输入区 -->
        <div class="text-input-section mb-6">
          <div class="mb-3">
            <n-text class="text-lg font-medium">输入文本内容</n-text>
          </div>
          <n-input
            v-model:value="formData.textContent"
            type="textarea"
            placeholder="请输入要转换为语音的文本内容..."
            :autosize="{ minRows: 6, maxRows: 12 }"
            :maxlength="2000"
            show-count
            clearable
          />
        </div>

        <!-- 高级设置 -->
        <n-collapse class="mb-6">
          <n-collapse-item title="高级设置" name="advanced">
            <div class="advanced-settings-container">
              <!-- 第一行：提示词和音色选择 -->
              <n-grid :cols="12" :x-gap="20" :y-gap="24" class="mb-6">
                <n-gi :span="isMobile ? 12 : 4">
                  <n-form-item label="提示词" label-placement="top">
                    <n-input
                      v-model:value="formData.prompt"
                      placeholder="默认 [oral_5]"
                      clearable
                    />
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 4">
                  <n-form-item label="快捷选择" label-placement="top">
                    <n-select
                      v-model:value="voicePreset"
                      :options="voicePresetOptions"
                      placeholder="选择预设音色"
                      clearable
                      @update:value="handlePresetChange"
                    >
                      <template #option="{ node, option }">
                        <div class="voice-preset-option">
                          <div class="preset-label">{{ option.label }}</div>
                          <div class="preset-description">{{ option.description }}</div>
                        </div>
                      </template>
                    </n-select>
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 4">
                  <n-form-item label="音色值" label-placement="top">
                    <n-input-number
                      v-model:value="customVoiceInput"
                      placeholder="自定义音色值"
                      :min="1"
                      :precision="0"
                      :show-button="true"
                      clearable
                      @update:value="handleCustomVoiceChange"
                      class="w-full"
                    />
                  </n-form-item>
                </n-gi>
              </n-grid>

              <!-- 第二行：滑块参数 -->
              <n-grid :cols="12" :x-gap="20" :y-gap="24" class="mb-6">
                <n-gi :span="isMobile ? 12 : 3">
                  <n-form-item :label="`速度 (${formData.speed})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.speed"
                      :min="1"
                      :max="100"
                      :step="1"
                      :marks="{
                        1: '1',
                        50: '50',
                        100: '100'
                      }"
                    />
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 3">
                  <n-form-item :label="`Temperature (${formData.temperature})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.temperature"
                      :min="0"
                      :max="1"
                      :step="0.1"
                      :marks="{
                        0: '0',
                        0.5: '0.5',
                        1: '1'
                      }"
                    />
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 3">
                  <n-form-item :label="`Top P (${formData.topP})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.topP"
                      :min="0"
                      :max="1"
                      :step="0.1"
                      :marks="{
                        0: '0',
                        0.5: '0.5',
                        1: '1'
                      }"
                    />
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 3">
                  <n-form-item :label="`Top K (${formData.topK})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.topK"
                      :min="1"
                      :max="50"
                      :step="1"
                      :marks="{
                        1: '1',
                        25: '25',
                        50: '50'
                      }"
                    />
                  </n-form-item>
                </n-gi>
              </n-grid>

              <!-- 第三行：Token设置 -->
              <n-grid :cols="12" :x-gap="20" :y-gap="24" class="mb-6">
                <n-gi :span="isMobile ? 12 : 6">
                  <n-form-item :label="`精炼最大Token (${formData.refineMaxNewToken})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.refineMaxNewToken"
                      :min="1"
                      :max="2048"
                      :step="1"
                      :marks="{
                        1: '1',
                        1024: '1024',
                        2048: '2048'
                      }"
                    />
                  </n-form-item>
                </n-gi>

                <n-gi :span="isMobile ? 12 : 6">
                  <n-form-item :label="`推理最大Token (${formData.inferMaxNewToken})`" label-placement="top">
                    <n-slider
                      v-model:value="formData.inferMaxNewToken"
                      :min="1"
                      :max="2048"
                      :step="1"
                      :marks="{
                        1: '1',
                        1024: '1024',
                        2048: '2048'
                      }"
                    />
                  </n-form-item>
                </n-gi>
              </n-grid>

              <!-- 第四行：选项设置 -->
              <n-grid :cols="12" :x-gap="20" :y-gap="24">
                <n-gi :span="12">
                  <n-form-item label="其他选项" label-placement="top">
                    <n-space>
                      <n-checkbox v-model:checked="formData.skipRefine">
                        跳过文本精炼步骤
                      </n-checkbox>
                    </n-space>
                  </n-form-item>
                </n-gi>
              </n-grid>
            </div>
          </n-collapse-item>
        </n-collapse>

        <!-- 操作按钮 -->
        <div class="action-bar">
          <n-button
            type="primary"
            size="large"
            :loading="isGenerating"
            :disabled="!formData.textContent.trim()"
            @click="handleGenerate"
          >
            <template #icon>
              <n-icon>
                <VolumeHighOutline />
              </n-icon>
            </template>
            {{ isGenerating ? '生成中...' : '开始生成' }}
          </n-button>

          <n-button
            size="large"
            :disabled="isGenerating"
            @click="handleClear"
          >
            清空内容
          </n-button>
        </div>

        <!-- 任务状态区 -->
        <div v-if="currentTask" class="task-status-section mt-6">
          <n-card title="任务状态" class="mb-4">
            <n-space vertical>
              <n-space align="center">
                <n-text>任务ID: {{ currentTask.id }}</n-text>
                <n-tag :type="getStatusType(currentTask.status)">
                  {{ currentTask.statusDesc }}
                </n-tag>
              </n-space>

              <n-progress
                :percentage="getProgressPercentage(currentTask.status)"
                :status="getProgressStatus(currentTask.status)"
                :show-indicator="false"
              />

              <div v-if="currentTask.status === 'PROCESSING'" class="flex items-center">
                <n-spin size="small" class="mr-2" />
                <n-text>正在处理中，请稍候...</n-text>
              </div>

              <div v-if="currentTask.errorMessage" class="error-message">
                <n-alert type="error" :bordered="false">
                  {{ currentTask.errorMessage }}
                </n-alert>
              </div>

              <!-- 完成后显示结果 -->
              <div v-if="currentTask.status === 'COMPLETED' && currentTask.fileUrl" class="result-section">
                <n-space vertical>
                  <div class="audio-player">
                    <audio controls class="w-full">
                      <source :src="currentTask.fileUrl" type="audio/mpeg">
                      您的浏览器不支持音频播放。
                    </audio>
                  </div>

                  <n-space>
                    <n-button secondary @click="downloadAudio(currentTask.fileUrl, currentTask.id)">
                      <template #icon>
                        <n-icon>
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
                          </svg>
                        </n-icon>
                      </template>
                      下载音频
                    </n-button>

                    <n-button secondary @click="shareAudio(currentTask.fileUrl)">
                      <template #icon>
                        <n-icon>
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M7.217 10.907a2.25 2.25 0 100 2.186m0-2.186c.18.324.283.696.283 1.093s-.103.77-.283 1.093m0-2.186l9.566-5.314a2.25 2.25 0 103.935 2.186 2.25 2.25 0 00-3.935 2.186l-9.566 5.314m0 0a2.25 2.25 0 103.933-2.185 2.25 2.25 0 00-3.933 2.185z" />
                          </svg>
                        </n-icon>
                      </template>
                      分享
                    </n-button>
                  </n-space>

                  <div v-if="currentTask.duration" class="task-info">
                    <n-descriptions size="small" :column="isMobile ? 1 : 2">
                      <n-descriptions-item label="音频时长">
                        {{ formatDuration(currentTask.duration) }}
                      </n-descriptions-item>
                      <n-descriptions-item label="处理耗时" v-if="currentTask.taskDurationWithoutWait">
                        {{ formatDuration(currentTask.taskDurationWithoutWait / 1000) }}
                      </n-descriptions-item>
                    </n-descriptions>
                  </div>
                </n-space>
              </div>
            </n-space>
          </n-card>
        </div>
          </div>
        </n-gi>

        <!-- 右侧：历史记录区 -->
        <n-gi :span="isMobile ? 12 : 4" v-if="!isMobile">
          <div class="history-area">
            <n-card title="历史记录" size="small" class="history-card">
              <template #header-extra>
                <n-space size="small">
                  <n-button
                    circle
                    secondary
                    size="small"
                    @click="refreshHistory"
                    :loading="historyLoading"
                  >
                    <template #icon>
                      <n-icon>
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                        </svg>
                      </n-icon>
                    </template>
                  </n-button>
                  <n-popconfirm @positive-click="clearAllHistory">
                    <template #trigger>
                      <n-button type="error" secondary size="small" circle>
                        <template #icon>
                          <n-icon>
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                              <path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                            </svg>
                          </n-icon>
                        </template>
                      </n-button>
                    </template>
                    确定要清空所有历史记录吗？
                  </n-popconfirm>
                </n-space>
              </template>

              <!-- 历史记录列表 -->
              <div class="history-list-container">
                <div v-if="historyLoading" class="loading-placeholder">
                  <div class="flex justify-center items-center py-8">
                    <n-spin size="medium" />
                  </div>
                </div>

                <div v-else-if="historyList.length === 0" class="empty-placeholder">
                  <n-empty description="暂无历史记录" size="small" />
                </div>

                <div v-else class="history-items">
                  <div
                    v-for="task in historyList.slice(0, 10)"
                    :key="task.id"
                    class="history-item"
                    @click="loadHistoryTask(task)"
                  >
                    <div class="history-item-header">
                      <n-space justify="space-between" align="center" size="small">
                        <n-tag :type="getStatusType(task.status)" size="small">
                          {{ task.statusDesc }}
                        </n-tag>
                        <n-text class="text-xs text-gray-400">
                          {{ formatRelativeTime(task.createdTime) }}
                        </n-text>
                      </n-space>
                    </div>

                    <div class="history-item-content">
                      <n-text class="text-sm" depth="3">
                        {{ truncateText(task.textContent, 60) }}
                      </n-text>
                    </div>

                    <div v-if="task.status === 'COMPLETED' && task.fileUrl" class="history-item-audio">
                      <div class="audio-mini-player">
                        <audio controls class="w-full" style="height: 24px;">
                          <source :src="task.fileUrl" type="audio/mpeg">
                        </audio>
                      </div>
                    </div>

                    <div class="history-item-actions">
                      <n-space size="small">
                        <n-button
                          v-if="task.status === 'COMPLETED' && task.fileUrl"
                          size="tiny"
                          secondary
                          @click.stop="downloadTaskAudio(task)"
                        >
                          下载
                        </n-button>
                        <n-button
                          size="tiny"
                          secondary
                          @click.stop="copyTaskText(task.textContent)"
                        >
                          复制
                        </n-button>
                        <n-popconfirm @positive-click="deleteTask(task.id)">
                          <template #trigger>
                            <n-button size="tiny" type="error" secondary @click.stop>
                              删除
                            </n-button>
                          </template>
                          确定删除这条记录吗？
                        </n-popconfirm>
                      </n-space>
                    </div>
                  </div>

                  <div v-if="historyList.length > 10" class="show-more">
                    <n-button text size="small" @click="showAllHistory">
                      查看全部 ({{ historyList.length }})
                    </n-button>
                  </div>
                </div>
              </div>
            </n-card>
          </div>
        </n-gi>

        <!-- 移动端历史记录 -->
        <n-gi :span="12" v-if="isMobile">
          <n-collapse class="mt-6">
            <n-collapse-item title="历史记录" name="history">
              <div class="mobile-history-list">
                <div v-if="historyLoading" class="loading-placeholder">
                  <div class="flex justify-center items-center py-8">
                    <n-spin size="medium" />
                  </div>
                </div>

                <div v-else-if="historyList.length === 0" class="empty-placeholder">
                  <n-empty description="暂无历史记录" size="small" />
                </div>

                <div v-else>
                  <div class="mb-4">
                    <n-space justify="space-between">
                      <n-text>共 {{ historyList.length }} 条记录</n-text>
                      <n-space size="small">
                        <n-button size="small" secondary @click="refreshHistory" :loading="historyLoading">
                          刷新
                        </n-button>
                        <n-popconfirm @positive-click="clearAllHistory">
                          <template #trigger>
                            <n-button type="error" secondary size="small">
                              清空
                            </n-button>
                          </template>
                          确定要清空所有历史记录吗？
                        </n-popconfirm>
                      </n-space>
                    </n-space>
                  </div>

                  <div class="mobile-history-items">
                    <div
                      v-for="task in historyList.slice(0, 5)"
                      :key="task.id"
                      class="mobile-history-item"
                    >
                      <div class="mobile-item-header">
                        <n-space justify="space-between" align="center">
                          <n-space size="small">
                            <n-tag :type="getStatusType(task.status)" size="small">
                              {{ task.statusDesc }}
                            </n-tag>
                            <n-text class="text-xs text-gray-400">
                              {{ formatRelativeTime(task.createdTime) }}
                            </n-text>
                          </n-space>
                        </n-space>
                      </div>

                      <div class="mobile-item-content">
                        <n-text class="text-sm" depth="3">
                          {{ truncateText(task.textContent, 100) }}
                        </n-text>
                      </div>

                      <div v-if="task.status === 'COMPLETED' && task.fileUrl" class="mobile-item-audio">
                        <audio controls class="w-full mt-2">
                          <source :src="task.fileUrl" type="audio/mpeg">
                        </audio>
                      </div>

                      <div class="mobile-item-actions">
                        <n-space size="small">
                          <n-button size="small" secondary @click="loadHistoryTask(task)">
                            载入
                          </n-button>
                          <n-button
                            v-if="task.status === 'COMPLETED' && task.fileUrl"
                            size="small"
                            secondary
                            @click="downloadTaskAudio(task)"
                          >
                            下载
                          </n-button>
                          <n-button size="small" secondary @click="copyTaskText(task.textContent)">
                            复制
                          </n-button>
                        </n-space>
                      </div>
                    </div>

                    <div v-if="historyList.length > 5" class="show-more">
                      <n-button text @click="showAllHistory">
                        查看全部历史记录 ({{ historyList.length }})
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </n-collapse-item>
          </n-collapse>
        </n-gi>
      </n-grid>
    </div>

    <!-- 分隔线 -->
    <n-divider />

    <!-- 使用说明 -->
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'
import { VolumeHighOutline } from '@vicons/ionicons5'
import PageCard from '@/components/PageCard.vue'
import UsageGuide from '@/components/UsageGuide.vue'
import { useBreakpoint } from '@/utils/responsive-helper'
import { createTTSTask, type CreateTTSTaskParams, type TTSTaskInfo, TTSTaskStatus } from '@/api/ai/tts'
import { ttsSyncService } from '@/utils/ai/tts-sync-service'
import { ttsStorage } from '@/utils/ai/tts-storage'

const message = useMessage()
const router = useRouter()
const { isMobile } = useBreakpoint()

// 表单数据
const formData = reactive<CreateTTSTaskParams>({
  textContent: '',
  prompt: '[oral_5]',
  temperature: 0.3,
  topP: 0.7,
  topK: 20,
  speed: 50,
  refineMaxNewToken: 384,
  inferMaxNewToken: 2048,
  skipRefine: false,
  customVoice: undefined
})

// 音色选择的局部状态
const voicePreset = ref<string | null>(null)
const customVoiceInput = ref<number | null>(null)

// 音色预设选项
const voicePresetOptions = [
  { 
    label: '大叔感男声（适合解说/旁白）',
    value: '2222',
    description: '偏成熟的“大叔感”，口型饱满、厚实'
  },
  { 
    label: '成熟男声（稳重，适合资讯播报）',
    value: '7869',
    description: '成熟男声（稳重），情绪起伏不大'
  },
  { 
    label: '低沉男声（适合纪录片/广告配音）',
    value: '6653',
    description: '成熟男声（偏低沉），更厚一些'
  },
  { 
    label: '明亮男声（适合教程/讲解）',
    value: '4099',
    description: '成熟男声（明亮些），表达清晰'
  },
  { 
    label: '温柔男声（适合故事/ASMR）',
    value: '5099',
    description: '温柔男声，语气更柔和'
  },
  { 
    label: '温柔女声（适合电台/陪伴类）',
    value: '1031',
    description: '音色轻柔细腻'
  },
  { 
    label: '知性女声（适合资讯解读/知识型）',
    value: '3798',
    description: '干净、理性'
  },
  { 
    label: '大舌头女声（趣味化效果）',
    value: '462',
    description: '轻微咬字特征，用于角色化/趣味化效果'
  },
  { 
    label: '庄重低沉男声（适合史诗台词）',
    value: '2424',
    description: '厚重有存在感，适合庄重/史诗感台词'
  }
]

// 状态管理
const isGenerating = ref(false)
const currentTask = ref<TTSTaskInfo | null>(null)

// 历史记录状态
const historyLoading = ref(false)
const historyList = ref<TTSTaskInfo[]>([])

// 处理预设选择
const handlePresetChange = (value: string | null) => {
  if (value) {
    customVoiceInput.value = parseInt(value, 10)
    formData.customVoice = parseInt(value, 10)
  }
}

// 处理自定义音色输入
const handleCustomVoiceChange = (value: number | null) => {
  if (value && value > 0) {
    formData.customVoice = value
    // 检查是否匹配某个预设
    const matchingPreset = voicePresetOptions.find(option => option.value === value.toString())
    if (matchingPreset) {
      voicePreset.value = value.toString()
    } else {
      voicePreset.value = null // 清除预设选择，表示为自定义值
    }
  } else {
    formData.customVoice = undefined
    voicePreset.value = null
  }
}

// 使用说明配置
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '在文本框中输入要转换为语音的文本内容（最多2000字）',
    '可选择展开高级设置，调整音色、温度参数等',
    '点击"开始生成"按钮创建语音任务',
    '等待任务完成后即可播放和下载生成的音频文件',
    '所有生成记录会自动保存到历史记录中'
  ],
  tips: [
    '文本内容应清晰易读，避免过多的特殊符号',
    '合理设置Temperature参数可以控制语音的多样性',
    '选择合适的音色可以获得更好的语音效果',
    '生成时间根据文本长度和服务器负载而定，请耐心等待'
  ],
  example: '示例文本：欢迎使用AI文本转语音功能，这是一个强大的语音合成工具。'
}

// 开始生成语音
const handleGenerate = async () => {
  if (!formData.textContent.trim()) {
    message.error('请输入文本内容')
    return
  }

  isGenerating.value = true
  currentTask.value = null

  try {
    // 创建任务
    const response = await createTTSTask(formData)
    const taskInfo = response.data
    message.success('任务创建成功，正在后台处理...')

    // 通过同步服务添加任务
    await ttsSyncService.addTask(taskInfo)
    currentTask.value = taskInfo
    
    message.info('任务已提交，将在后台继续处理，您可以关闭页面')

  } catch (error) {
    console.error('生成失败:', error)
    message.error((error as Error).message || '生成失败，请稍后重试')
  } finally {
    isGenerating.value = false
  }
}

// 清空内容
const handleClear = () => {
  formData.textContent = ''
  formData.prompt = '[oral_5]'
  formData.temperature = 0.3
  formData.topP = 0.7
  formData.topK = 20
  formData.speed = 50
  formData.refineMaxNewToken = 384
  formData.inferMaxNewToken = 2048
  formData.skipRefine = false
  formData.customVoice = undefined
  voicePreset.value = null
  customVoiceInput.value = null
  currentTask.value = null
}

// 下载音频
const downloadAudio = async (url: string, taskId: number) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const downloadUrl = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = `tts_audio_${taskId}.mp3`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    URL.revokeObjectURL(downloadUrl)
    message.success('开始下载音频文件')
  } catch (error) {
    console.error('下载失败:', error)
    message.error('下载失败，请稍后重试')
  }
}

// 分享音频
const shareAudio = async (url: string) => {
  try {
    if (navigator.share) {
      await navigator.share({
        title: 'AI生成的语音',
        text: '来听听这个AI生成的语音吧！',
        url: url
      })
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(url)
      message.success('音频链接已复制到剪贴板')
    }
  } catch (error) {
    console.error('分享失败:', error)
    message.error('分享失败')
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case TTSTaskStatus.PENDING:
      return 'info'
    case TTSTaskStatus.PROCESSING:
      return 'warning'
    case TTSTaskStatus.COMPLETED:
      return 'success'
    case TTSTaskStatus.FAILED:
      return 'error'
    default:
      return 'default'
  }
}

// 获取进度百分比
const getProgressPercentage = (status: string) => {
  switch (status) {
    case TTSTaskStatus.PENDING:
      return 10
    case TTSTaskStatus.PROCESSING:
      return 50
    case TTSTaskStatus.COMPLETED:
      return 100
    case TTSTaskStatus.FAILED:
      return 100
    default:
      return 0
  }
}

// 获取进度状态
const getProgressStatus = (status: string) => {
  switch (status) {
    case TTSTaskStatus.FAILED:
      return 'error'
    case TTSTaskStatus.COMPLETED:
      return 'success'
    default:
      return 'info'
  }
}

// 格式化时长
const formatDuration = (seconds: number) => {
  if (seconds < 60) {
    return `${seconds.toFixed(1)}秒`
  } else {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}分${remainingSeconds.toFixed(1)}秒`
  }
}

// 初始加载历史记录
const loadHistory = () => {
  // 从同步服务获取缓存的任务列表
  historyList.value = ttsSyncService.getCachedTasks()
}

// 刷新历史记录
const refreshHistory = () => {
  historyLoading.value = true
  // 触发同步服务重新加载
  ttsSyncService.startSync().then(() => {
    historyLoading.value = false
  })
}

// 清空所有历史记录
const clearAllHistory = async () => {
  try {
    await ttsSyncService.clearAllTasks()
    message.success('历史记录已清空')
  } catch (error) {
    console.error('清空历史记录失败:', error)
    message.error('清空历史记录失败')
  }
}

// 删除单条记录
const deleteTask = async (taskId: number) => {
  try {
    await ttsSyncService.deleteTask(taskId)
    message.success('记录已删除')
  } catch (error) {
    console.error('删除记录失败:', error)
    message.error('删除记录失败')
  }
}

// 下载任务音频
const downloadTaskAudio = async (task: TTSTaskInfo) => {
  if (!task.fileUrl) return

  try {
    const response = await fetch(task.fileUrl)
    const blob = await response.blob()
    const downloadUrl = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = `tts_audio_${task.id}.mp3`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    URL.revokeObjectURL(downloadUrl)
    message.success('开始下载音频文件')
  } catch (error) {
    console.error('下载失败:', error)
    message.error('下载失败，请稍后重试')
  }
}

// 复制任务文本
const copyTaskText = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    message.success('文本已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败')
  }
}

// 加载历史任务到当前表单
const loadHistoryTask = (task: TTSTaskInfo) => {
  formData.textContent = task.textContent
  formData.prompt = task.prompt || '[oral_5]'
  formData.temperature = task.temperature || 0.3
  formData.topP = task.topP || 0.7
  formData.topK = task.topK || 20
  formData.speed = task.speed || 50
  formData.refineMaxNewToken = task.refineMaxNewToken || 384
  formData.inferMaxNewToken = task.inferMaxNewToken || 2048
  formData.skipRefine = task.skipRefine || false
  formData.customVoice = task.customVoice
  
  // 更新音色选择状态
  if (task.customVoice) {
    const voiceValue = task.customVoice.toString()
    customVoiceInput.value = task.customVoice
    // 检查是否匹配某个预设
    const matchingPreset = voicePresetOptions.find(option => option.value === voiceValue)
    voicePreset.value = matchingPreset ? voiceValue : null
  } else {
    customVoiceInput.value = null
    voicePreset.value = null
  }

  message.success('已加载历史任务参数')
}

// 显示全部历史记录（移动端展开历史记录折叠面板）
const showAllHistory = () => {
  // 在移动端，可以滚动到历史记录区域
  if (isMobile.value) {
    const historyElement = document.querySelector('.mobile-history-list')
    if (historyElement) {
      historyElement.scrollIntoView({ behavior: 'smooth' })
    }
  }
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 格式化相对时间
const formatRelativeTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60 * 1000) {
    return '刚刚'
  } else if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  } else if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  } else {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
}

// 事件监听器定义
let handleTaskUpdate: ((taskInfo: TTSTaskInfo) => void) | null = null
let handleTaskListUpdate: ((tasks: TTSTaskInfo[]) => void) | null = null

// 组件挂载时加载历史记录
onMounted(async () => {
  // 初始加载历史记录
  loadHistory()
  
  // 监听任务更新事件
  handleTaskUpdate = (taskInfo: TTSTaskInfo) => {
    // 如果是当前正在处理的任务，更新当前状态
    if (currentTask.value && currentTask.value.id === taskInfo.id) {
      currentTask.value = taskInfo
      
      // 根据状态显示消息
      if (taskInfo.status === TTSTaskStatus.COMPLETED) {
        message.success(`任务 ${taskInfo.id} 已完成！`)
      } else if (taskInfo.status === TTSTaskStatus.FAILED) {
        message.error(`任务 ${taskInfo.id} 执行失败: ${taskInfo.errorMessage || '未知错误'}`)
      }
    }
  }
  
  // 监听任务列表更新事件
  handleTaskListUpdate = (tasks: TTSTaskInfo[]) => {
    // 直接更新列表，不重新加载
    historyList.value = tasks
  }
  
  // 注册事件监听器
  ttsSyncService.on('taskUpdate', handleTaskUpdate)
  ttsSyncService.on('taskListUpdate', handleTaskListUpdate)
  
  // 确保同步服务已启动
  await ttsSyncService.startSync()
  
  // 检查未完成的任务
  const incompleteTasks = historyList.value.filter(
    task => task.status === TTSTaskStatus.PENDING || task.status === TTSTaskStatus.PROCESSING
  )
  if (incompleteTasks.length > 0) {
    message.info(`发现 ${incompleteTasks.length} 个未完成的任务，正在后台处理...`)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除事件监听器
  if (handleTaskUpdate) {
    ttsSyncService.off('taskUpdate', handleTaskUpdate)
  }
  if (handleTaskListUpdate) {
    ttsSyncService.off('taskListUpdate', handleTaskListUpdate)
  }
})
</script>

<style scoped lang="less">
.tool-container {
  max-width: 1400px;
  margin: 0 auto;
}

.tts-function-area {
  // TTS功能区域样式
}

.action-bar {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin: 24px 0;

  @media (max-width: 768px) {
    flex-direction: column;

    .n-button {
      width: 100%;
    }
  }
}

.task-status-section {
  .result-section {
    background: rgba(255, 105, 180, 0.05);
    padding: 16px;
    border-radius: 8px;

    .audio-player audio {
      max-width: 100%;
    }
  }

  .task-info {
    margin-top: 12px;

    :deep(.n-descriptions-item-label) {
      font-weight: 500;
    }
  }
}

.error-message {
  margin-top: 8px;
}

// 历史记录区域
.history-area {
  height: fit-content;
  max-height: 80vh;

  .history-card {
    height: 100%;

    :deep(.n-card__content) {
      padding: 12px;
      max-height: 70vh;
      overflow-y: auto;
    }
  }

  .history-list-container {
    .history-items {
      .history-item {
        padding: 12px;
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        margin-bottom: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: #ff69b4;
          background: rgba(255, 105, 180, 0.05);
        }

        .history-item-header {
          margin-bottom: 8px;
        }

        .history-item-content {
          margin-bottom: 8px;
          line-height: 1.4;
        }

        .history-item-audio {
          margin-bottom: 8px;

          .audio-mini-player {
            audio {
              width: 100%;
              height: 24px;
            }
          }
        }

        .history-item-actions {
          display: flex;
          justify-content: flex-end;
        }
      }

      .show-more {
        text-align: center;
        padding: 8px;
        border-top: 1px solid #f0f0f0;
      }
    }
  }
}

// 移动端历史记录
.mobile-history-list {
  .mobile-history-items {
    .mobile-history-item {
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      margin-bottom: 12px;

      .mobile-item-header {
        margin-bottom: 8px;
      }

      .mobile-item-content {
        margin-bottom: 8px;
        line-height: 1.4;
      }

      .mobile-item-audio {
        margin-bottom: 8px;
      }

      .mobile-item-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 8px;
      }
    }

    .show-more {
      text-align: center;
      padding: 8px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.loading-placeholder, .empty-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100px;
}

// 折叠面板样式优化
:deep(.n-collapse) {
  .n-collapse-item__header {
    font-weight: 500;
    padding: 12px 16px;
    background: rgba(255, 105, 180, 0.03);
    border-radius: 8px;
    margin-bottom: 4px;
    
    &:hover {
      background: rgba(255, 105, 180, 0.06);
    }
  }
  
  .n-collapse-item__content-wrapper {
    .n-collapse-item__content-inner {
      padding: 16px;
    }
  }
}

// 高级设置容器样式
.advanced-settings-container {
  padding: 8px 0;
  
  :deep(.n-form-item) {
    margin-bottom: 0;
    
    .n-form-item-label {
      font-size: 14px;
      font-weight: 500;
      color: var(--n-text-color);
      padding-bottom: 8px;
      display: block;
      
      // 统一标签高度，确保对齐
      min-height: 32px;
      line-height: 1.5;
    }
  }
  
  :deep(.n-input) {
    font-size: 14px;
  }
  
  :deep(.n-select) {
    font-size: 14px;
  }
  
  :deep(.n-input-number) {
    width: 100%;
    
    .n-input-number__input {
      font-size: 14px;
    }
  }
  
  :deep(.n-slider) {
    padding: 0 8px;
    margin-top: 4px;
    
    .n-slider-rail {
      background: rgba(255, 105, 180, 0.1);
    }
    
    .n-slider-fill {
      background: linear-gradient(90deg, #ff69b4, #ff1493);
    }
    
    .n-slider-handle {
      border-color: #ff69b4;
    }
    
    .n-slider-marks {
      font-size: 12px;
      color: var(--n-text-color-3);
      margin-top: 8px;
    }
  }
  
  // 响应式网格间距
  .n-grid {
    @media (max-width: 768px) {
      .n-gi + .n-gi {
        margin-top: 16px;
      }
    }
  }
}

// 音色预设选项样式
.voice-preset-option {
  .preset-label {
    font-weight: 500;
    color: var(--n-text-color);
    margin-bottom: 2px;
  }
  
  .preset-description {
    font-size: 12px;
    color: var(--n-text-color-3);
    line-height: 1.3;
  }
}

@media (prefers-color-scheme: dark) {
  .result-section {
    background: rgba(255, 105, 180, 0.1) !important;
  }

  .history-area {
    .history-item {
      border-color: rgba(255, 255, 255, 0.1) !important;

      &:hover {
        background: rgba(255, 105, 180, 0.1) !important;
      }
    }
  }

  .mobile-history-list {
    .mobile-history-item {
      border-color: rgba(255, 255, 255, 0.1) !important;
    }
  }
  
  // 深色模式下的高级设置样式
  :deep(.n-collapse) {
    .n-collapse-item__header {
      background: rgba(255, 105, 180, 0.05);
      
      &:hover {
        background: rgba(255, 105, 180, 0.08);
      }
    }
  }
  
  .advanced-settings-container {
    :deep(.n-slider) {
      .n-slider-rail {
        background: rgba(255, 105, 180, 0.15);
      }
      
      .n-slider-fill {
        background: linear-gradient(90deg, #ff69b4, #ff1493);
      }
    }
  }
}
</style>
